package oa.struts.action;

import java.util.Collection;
import java.util.Date;

import javax.annotation.Resource;

import oa.domain.forum.Forum;
import oa.domain.forum.Reply;
import oa.domain.forum.Topic;
import oa.domain.page.PageBean;
import oa.service.ForumService;
import oa.service.ReplyService;
import oa.service.TopicService;
import oa.struts.action.base.BaseAction;
import oa.util.HQLHelper;
import oa.util.OAUtils;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
@Controller("topicAction")
public class TopicAction extends BaseAction<Topic> {

	@Resource(name="forumService")
	private ForumService forumService;
	@Resource(name="topicService")
	private TopicService topicService;
	@Resource(name="replyService")
	private ReplyService replyService;
	
	private Long forumId;
	
	public Long getForumId() {
		return forumId;
	}
	public void setForumId(Long forumId) {
		this.forumId = forumId;
	}
	/**
	 * 显示单个主题（回复列表）
	 * @return
	 */
	public String showTopicById()
	{
		//根据id查询主题
		Topic topic =  this.topicService.getTopicById(this.getModel().getId());
		ActionContext.getContext().getValueStack().push(topic);
		//根据主题查询对应的回复列表
//		Collection<Reply> replyList = this.replyService.getReplyByTopic(this.getModel());
//		ActionContext.getContext().put("replyList", replyList);
//		PageBean pageBean  = replyService.getPageBean(currentPage,topic);
		HQLHelper hh = new HQLHelper(Reply.class);
		hh.addWhere("o.topic = ?", topic);
		hh.addOrderBy("o.postTime", true);
		PageBean pageBean = replyService.getPageBean(hh, currentPage);
		ActionContext.getContext().getValueStack().push(pageBean);
		return listAction;
	}
	/**
	 * 跳转到主题发表页面
	 * @return
	 */
	public String addUI()
	{
		//根据id查询主题
		Forum forum = this.forumService.getForumById(forumId);
		ActionContext.getContext().getValueStack().push(forum);
		return addUI;
 	}
	/**
	 * 发表主题
	 * @return
	 */
	public String add()
	{
		Topic topic = new Topic();
		BeanUtils.copyProperties(this.getModel(), topic);
		topic.setForum(this.forumService.getForumById(forumId));//主题关联版块
		topic.setAuthor(OAUtils.getUserFromSession());//设置主题的作者为当前登录用户
		topic.setPostTime(new Date());//当前主题的发布时间
		topic.setLastUpdateTime(topic.getPostTime());//设置最后更新时间为发表主题的时间
		topic.setIpAddress(OAUtils.getIpAddress());//设置客户端的ip地址
		topic.setReplyCount(0);//设置当前主题的回复数量为0
		topic.setType(0);//主题的类型为普通帖
		topic.setLastReply(null);//默认没有回复
		this.topicService.saveTopic(topic);
		return action2action;
	}
	
}
